#include "sd_diskio.h"
#include "stm32f4xx_hal.h"
#include "stm32f4xx_hal_sd.h"


// 假设 hsd 是外部定义的全局变量
extern SD_HandleTypeDef hsd;

static volatile DSTATUS Stat = STA_NOINIT;

uint8_t BSP_SD_GetCardState(void)
{
  return((HAL_SD_GetCardState(&hsd) == HAL_SD_CARD_TRANSFER ) ? SD_TRANSFER_OK : SD_TRANSFER_BUSY);
}

uint8_t BSP_SD_ReadBlocks(uint32_t *pData, uint32_t ReadAddr, uint32_t NumOfBlocks, uint32_t Timeout)
{
  if(HAL_SD_ReadBlocks(&hsd, (uint8_t *)pData, ReadAddr, NumOfBlocks, Timeout) != HAL_OK){
    return MSD_ERROR;
  }else{
    return MSD_OK;
  }
}

uint8_t BSP_SD_WriteBlocks(uint32_t *pData, uint32_t WriteAddr, uint32_t NumOfBlocks, uint32_t Timeout)
{
  if(HAL_SD_WriteBlocks(&hsd, (uint8_t *)pData, WriteAddr, NumOfBlocks, Timeout) != HAL_OK){
    return MSD_ERROR;
  }else{
    return MSD_OK;
  }
}
DSTATUS SD_CheckStatus(void)
{
    Stat = STA_NOINIT;

    if(BSP_SD_GetCardState() == MSD_OK)
    {
        Stat &= ~STA_NOINIT;
    }
  
    return Stat;
}

DSTATUS SD_status(void)
{
  return SD_CheckStatus();
}

DSTATUS SD_initialize(void)
{

    Stat = SD_CheckStatus();

    if (Stat & STA_NOINIT) {
        return Stat;
    }
    return Stat;
}

DRESULT SD_read(BYTE *buff, LBA_t sector, UINT count)
{
    DRESULT res = RES_ERROR;

    if(BSP_SD_ReadBlocks((uint32_t*)buff,(uint32_t)sector,count, 100) == MSD_OK)
    {
        uint32_t timeout = HAL_GetTick() + 500; 
        while(BSP_SD_GetCardState()!= MSD_OK) {
            if (HAL_GetTick() > timeout) {
                return RES_ERROR;
            }
        }
      res = RES_OK;
    }
    return res;
}

DRESULT SD_write(const BYTE *buff, LBA_t sector, UINT count)
{
    DRESULT res = RES_ERROR;

    if(BSP_SD_WriteBlocks((uint32_t*)buff,(uint32_t)sector,count,100) == MSD_OK)
    {
      while(BSP_SD_GetCardState() != MSD_OK){
      }
      res = RES_OK;
    }
    return res;
}
